package com.dragon.shop_user.service.impl;

import com.dragon.shop_common.utils.AjaxResult;
import com.dragon.shop_user.entity.UserInfo;
import com.dragon.shop_user.feign.OrderFeign;
import com.dragon.shop_user.mapper.UserInfoMapper;
import com.dragon.shop_user.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Baomidou
 * @since 2025-03-20
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private OrderFeign orderFeign;

    @Override
    @GlobalTransactional
    public AjaxResult<Void> createOrder() {
        try {
            // UserInfo userInfo = new UserInfo();
            // userInfo.setName("测试分布式锁");
            // userInfo.setBlance(new BigDecimal("100"));
            // userInfoMapper.insert(userInfo);

            String userId = "1";

            boolean flag = userInfoMapper.decrBlance(BigDecimal.valueOf(10), userId) > 0;
            if (!flag) {
                return AjaxResult.failed("账户余额扣除失败");
            }

            AjaxResult<String> result = orderFeign.createOrder(userId);
            if (!result.getIsSuccessful()) {
                // 如果是业务上返回的失败需要主动抛出异常
                throw new RuntimeException("订单创建失败呀");
            }

            return AjaxResult.succeed();
        } catch (Exception e) {
            throw new RuntimeException("订单创建失败");
        }

    }
}
